package com.huaxin.hxcloud.activity;

import android.app.Dialog;
import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.emmp_ard.scancapture.ScanCaptureActivity;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Entity.DriverListDTO;
import com.huaxin.common.Entity.VehicleRecord;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.DialogUtil;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.BottomSheetDialog;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.dialog.DatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * @desc 行车记录actiity
 */
public class VehicleMgtActivity extends BaseActivity {

    VehicleRecordListAdapter vehicleRecordListAdapter;

    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM");

    @BindView(R.id.img)
    ImageView    img;
    @BindView(R.id.bind_info1)
    TextView     bindInfo1;
    @BindView(R.id.bind_info2)
    TextView     bindInfo2;
    @BindView(R.id.btn_back_car)
    Button       btn_back_car;
    @BindView(R.id.month)
    TextView     month;
    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appBar;
    @BindView(R.id.list_view)
    RecyclerView rcl_vehicle_record;


    public String mPlateNum;
    public String mVehicleModel;
    public Long   mBindDate;
    public Date mTempDate = new Date();
    private boolean mBindState;
    Calendar calendar = Calendar.getInstance();
    private View mNoDataView;

    private List mVehicleDatas;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_vehicle_mgt;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        super.initView();
        mVehicleDatas = new ArrayList();
        setSupportActionBar(toolbar);
        vehicleRecordListAdapter = new VehicleRecordListAdapter();
        rcl_vehicle_record.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        rcl_vehicle_record.setAdapter(vehicleRecordListAdapter);

        mNoDataView = LayoutInflater.from(this).inflate(R.layout.item_empty_face_top, (ViewGroup) rcl_vehicle_record.getParent(), false);
        updateView();

        setOnItemClickListener();

    }

    /**
     * 添加条目点击事件
     */
    private void setOnItemClickListener() {
        vehicleRecordListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {

                if (mVehicleDatas.get(position) instanceof VehicleRecord) {
                    VehicleRoutActivity.start(VehicleMgtActivity.this, (VehicleRecord) mVehicleDatas
                            .get(position));
                }
            }
        });
    }

    @Override
    public void requestData() {
        calendar.setTime(new Date());
        ApiVehicleDriverList(LOADING, calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH) + 1);
        requestAddress(BaseApp.getLatLng());
    }

    /**
     * 提交经纬度
     *
     * @param latLng
     */
    private void requestAddress(LatLng latLng) {
        //避免latlng为null的情况下空指针
        if (latLng == null)
            return;

        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().commitLngLat(latLng.longitude, latLng.latitude);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                Log.d(TAG, "onResponse:---> " + response.isSuccessful());
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                Log.d(TAG, "onResponse: " + t);
            }
        });

    }

    /*请求获取用车记录列表*/
    private void ApiVehicleDriverList(int status, final Integer year, final Integer month) {
        updateLoadStatus(status);
        Call<DriverListDTO> call = HxTransmitRequestHelper.getRequestApi().vehicleDriverList(year, month);
        autoClose(call);
        call.enqueue(new Callback<DriverListDTO>() {
            @Override
            public void onResponse(Call<DriverListDTO> call, Response<DriverListDTO> response) {

                if (response.isSuccessful()) {
                    DriverListDTO driverList = response.body();
                    if (driverList != null && driverList.isSuccessful()) {

                        mVehicleDatas.clear();
                        updateLoadStatus(LOAD_SUCCESS);
                        //当前使用车辆
                        VehicleRecord driver = driverList.getVehicleDriver();
                        if (driver != null) {
                            mPlateNum = driver.getLicensePlateNum();
                            mVehicleModel = driver.getVehicleModel();
                            mBindDate = driver.getBindDate();
                            mBindState = true;
                            if (mPlateNum != null && mBindDate != null && (format.format(mBindDate).equals(format.format(mTempDate)))) {
                                mVehicleDatas.add(driver);
                            }
                        } else {
                            mBindState = false;
                        }

                        List<VehicleRecord> vehicleDriverListBack = driverList
                                .getVehicleDriverListBack();
                        //判断之前用车还车记录
                        if (vehicleDriverListBack != null && vehicleDriverListBack.size() > 0) {
                            mVehicleDatas.addAll(vehicleDriverListBack);
                        }

                        vehicleRecordListAdapter.setNewData(mVehicleDatas);

                        //如果数据为空，必须先把数据添加到adapter中，再设置空布局，不然会报数组越界异常
                        if (mVehicleDatas.size() == 0)
                            vehicleRecordListAdapter.setEmptyView(mNoDataView);

                        updateView();
                        return;
                    }
                }
                updateLoadStatus(LOAD_ERROR);
            }

            @Override
            public void onFailure(Call<DriverListDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });
    }

    private void updateView() {
        if (mPlateNum != null && mBindDate != null) {
            toolbar.setTitle("还车");
            loadText(bindInfo1, mPlateNum);
            loadText(bindInfo2, TextUtils.isEmpty(mVehicleModel) ? "该车辆未录入车库数据" : mVehicleModel);
            // btn_back_car.setImageResource(R.drawable.icon_car_back);
            btn_back_car.setText("还车");
            mBindState = true;
        } else {
            toolbar.setTitle("出车");
            bindInfo1.setText("当前暂无用车");
            loadText(bindInfo2, String.format("本月已用车%d次", mVehicleDatas.size()));
            btn_back_car.setText("出车");
            mBindState = false;
        }
        month.setText(format.format(mTempDate));
        //        vehicleRecordListAdapter.notifyDataSetChanged();
    }


    /*还车接口请求*/
    private void ApiUnbindVehicle() {
        final Dialog dialog = DialogUtil.getWaitDialog(this, "请稍等");
        dialog.show();
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().unbindVehicle(mPlateNum, null);
        autoClose(call);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                dialog.dismiss();
                if (response.isSuccessful()) {
                    BaseDTO baseDTO = response.body();
                    if (baseDTO != null && baseDTO.isSuccessful()) {
                        mPlateNum = null;
                        mVehicleModel = null;
                        mBindState = false;
                        ApiVehicleDriverList(LOAD_NO_WORK, calendar.get(Calendar.YEAR),
                                calendar.get(Calendar.MONTH) + 1);
                        //updateView();
                        return;
                    }
                }
                ToastUtil.showToast("还车失败");

            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                dialog.dismiss();
                ToastUtil.showToast("还车失败");
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constants.RET_SEARCH || requestCode == Constants.RET_SWEEP) {
                mPlateNum = data.getStringExtra(Constants.IK_PLATE_NUM);
                mVehicleModel = data.getStringExtra(Constants.IK_VEHICLE_MODEL);
                mBindDate = System.currentTimeMillis();
                ApiVehicleDriverList(LOAD_NO_WORK, calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH) + 1);

            }

        }
    }

    @OnClick({R.id.btn_back_car, R.id.month})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back_car:
                if (mBindState) {
                    ApiUnbindVehicle();
                } else {
                    final String[] array = {"搜索车辆", "车牌扫描"};
                    BottomSheetDialog dialog = new BottomSheetDialog(this, array, new
                            BottomSheetDialog.OnItemClickListener() {

                                @Override
                                public void onItemClick(int position) {
                                    if (position == 0) {
                                        CommonSearchActivity.start(VehicleMgtActivity.this,
                                                CommonSearchActivity
                                                        .MODE_SEARCH_PLATE);
                                    } else {
                                        ScanCaptureActivity.start(VehicleMgtActivity.this,
                                                ScanCaptureActivity.TYPE_PLATE_NUM,
                                                ScanCaptureActivity
                                                        .MODE_BIND_CAR);
                                    }
                                }
                            });
                    dialog.show();
                }
                break;
            case R.id.month:
                DatePickerDialog picker = new DatePickerDialog(this, mTempDate, new
                        DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(Date date) {
                                mTempDate = date;
                                month.setText(format.format(mTempDate));
                                calendar.setTime(date);
                                ApiVehicleDriverList(LOADING, calendar.get(Calendar.YEAR),
                                        calendar.get
                                                (Calendar.MONTH) + 1);
                            }
                        });
                picker.show();
                break;
        }
    }

    class VehicleRecordListAdapter extends BaseQuickAdapter<VehicleRecord, BaseViewHolder> {

        public VehicleRecordListAdapter() {
            super(R.layout.item_out_record);
        }

        @Override
        protected void convert(BaseViewHolder viewHolder, VehicleRecord vehicleRecord) {
            TextView date = viewHolder.getView(R.id.date);
            TextView plate = viewHolder.getView(R.id.plate);
            TextView model = viewHolder.getView(R.id.model);

            loadText(plate, vehicleRecord.getLicensePlateNum());
            String info;
            if (vehicleRecord.getEndDate() == null) {
                info = "使用中";
                model.setTextColor(getResources().getColor(R.color.state_green));
            } else {
                info = "未使用";
                model.setTextColor(getResources().getColor(R.color.text_color_2));
            }
            loadText(model, info);
            loadText(date, dateFormat(vehicleRecord.getBindDate(), "yyyy/MM/dd"));
        }

    }
}
